<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>myRedux</title>
</head>
<body>
  <button id="plus">+1</button>
  <span id="count">0</span>
  <button id="minus">-1</button>
  <script src="./myRedux.js"></script>
  <script>
    function enhancer(createStore) {
      return function (reducer, preloadedState) {
        var store = createStore(reducer, preloadedState)
        var dispatch = store.dispatch
        function _dispatch (action) {
          if (typeof action === 'function') {
            return action(dispatch)
          }
          dispatch(action)
        }
        return {
          ...store,
          dispatch: _dispatch
        }
      }
    }

    const reducer = (state, action) => {
      switch (action.type) {
        case 'increment':
          return state + 1
        case 'decrement':
          return state - 1
        default:
          return state
      }
    }

    
    // 创建 store 
    // const store = createStore(reducer, 0, enhancer);
    const store = createStore(reducer, 0, applyMiddleware(logger, thunk));
    console.log(store)
    // 订阅状态的变化
    store.subscribe(() => {
      document.getElementById('count').innerHTML = store.getState()
    });

    // 加按钮触发 action 让数值 加一
    document.getElementById('plus').addEventListener('click', function (e) {
      // store.dispatch({type: 'increment'})
      store.dispatch(function (dispatch) {
        setTimeout(() => {
          dispatch({ type: 'increment' })
        }, 1000);
      })
    })
    // 减按钮触发 action 让数值 减一
    document.getElementById('minus').addEventListener('click', function (e) {
      store.dispatch({type: 'decrement'})
    });
  </script>
</body>
</html>